<template>
  <div class="app-container">
    <!-- 产品列表区域 -->
    <el-card class="app-card" :body-style="{ padding: '24px' }">
      <div class="search-bar">
        <el-input
          v-model="queryParams.product_name"
          placeholder="请输入产品名称"
          class="search-input"
          clearable
          @keyup.enter="handleQuery"
        />
        <el-input
          v-model="queryParams.product_tag"
          placeholder="请输入产品标签"
          class="search-input"
          clearable
          @keyup.enter="handleQuery"
        />
        <el-button type="primary" class="search-button" @click="handleQuery">搜索</el-button>
        <el-button class="reset-button" @click="resetQuery">重置</el-button>
      </div>
      
      <div class="table-header">
        <div class="left-buttons">
          <el-button type="primary" class="action-button add-button" @click="handleAdd">
            <el-icon class="button-icon"><plus /></el-icon>添加
          </el-button>
          <el-button type="danger" class="action-button" :disabled="selectedProducts.length === 0" @click="handleBatchDelete" v-if="hasDeletePermission">
            <el-icon class="button-icon"><delete /></el-icon>批量删除
          </el-button>
        </div>
        <div class="right-buttons">
          <el-button type="success" class="action-button export-button" @click="handleExport">
            <el-icon class="button-icon"><download /></el-icon>导出
          </el-button>
          <el-button type="primary" class="action-button import-button" @click="handleImport" v-if="hasEditPermission">
            <el-icon class="button-icon"><upload /></el-icon>导入
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="productList"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%"
        class="data-table"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="操作" width="150" fixed="left">
          <template #default="scope">
            <el-button type="primary" link class="table-button" @click="handleEdit(scope.row)" v-if="hasEditPermission">编辑</el-button>
            <el-button type="danger" link class="table-button" @click="handleDelete(scope.row)" v-if="hasDeletePermission">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="产品名称" width="180" />
        <el-table-column label="产品标签" width="220">
          <template #default="scope">
            <div class="tag-container">
            <el-tag 
              v-for="tag in getProductTags(scope.row.product_tag)" 
              :key="tag" 
              :type="getTagType(tag)"
                class="product-tag"
            >
              {{ tag }}
            </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="commission_category_name" label="提成分类" min-width="150" />
      </el-table>
      
      <div class="table-pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑产品弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      destroy-on-close
      class="custom-dialog"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="产品名称" prop="product_name">
          <el-input v-model="productForm.product_name" placeholder="请输入产品名称" class="form-input" />
        </el-form-item>
        <el-form-item label="产品标签" prop="product_tag">
          <el-input v-model="productForm.product_tag" placeholder="请输入产品标签，多个标签用英文逗号分隔" class="form-input" />
          <div class="form-tip">多个标签用英文逗号分隔，如：标签1,标签2,标签3</div>
        </el-form-item>
        <el-form-item label="提成分类" prop="commission_category">
          <el-select v-model="productForm.commission_category" placeholder="请选择提成分类" class="form-input">
            <el-option
              v-for="item in commissionCategoryOptions"
              :key="item.id"
              :label="item.commission_category"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="cancel-button" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" class="submit-button" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入产品数据对话框 -->
    <el-dialog
      title="导入产品数据"
      v-model="importDialogVisible"
      width="500px"
      destroy-on-close
      class="custom-dialog"
    >
      <div class="import-container">
        <div class="import-tips">
          <p>温馨提示：</p>
          <ol>
            <li>请先下载导入模板，按照模板格式填写数据后上传</li>
            <li>支持Excel格式文件(.xlsx, .xls)</li>
            <li>数据量较大时请耐心等待</li>
          </ol>
        </div>
        
        <div class="template-download">
          <el-button type="primary" link class="download-button" @click="downloadTemplate">
            <el-icon class="button-icon"><download /></el-icon>下载导入模板
          </el-button>
        </div>
        
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-drop="handleDrop"
          :on-exceed="handleExceed"
          :limit="1"
          :accept="'.xlsx,.xls'"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传Excel文件(.xlsx, .xls)，产品名称必须唯一
            </div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button class="cancel-button" @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" class="submit-button" @click="submitImport" :loading="importLoading">
            开始导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getProductList, getProduct, createProduct, updateProduct, deleteProduct, batchDeleteProducts, exportProducts, getImportTemplate, importProducts } from '@/api/products';
import { getCommissionCategoryList } from '@/api/commission-categories';
import { UploadFilled, Download, Upload, Plus, Delete } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import { canEdit, canDelete } from '@/utils/permissions';

// 查询参数
const queryParams = reactive({
  product_name: '',
  product_tag: '',
  page: 1,
  page_size: 10
});

// 表格数据
const productList = ref([]);
const loading = ref(false);
const selectedIds = ref([]);

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 表单相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加产品');
const productForm = reactive({
  product_name: '',
  product_tag: '',
  commission_category: null
});

// 提成分类选项
const commissionCategoryOptions = ref([]);

// 导入相关
const importDialogVisible = ref(false);
const importLoading = ref(false);
const uploadRef = ref(null);
const importFile = ref(null);

// 表单规则
const rules = {
  product_name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  commission_category: [{ required: true, message: '请选择提成分类', trigger: 'change' }]
};

const productFormRef = ref(null);

// 新增 router 和 route
const route = useRoute();

// 计算属性：是否可以编辑
const hasEditPermission = computed(() => {
  return canEdit(route.path);
});

// 计算属性：是否可以删除
const hasDeletePermission = computed(() => {
  return canDelete(route.path);
});

// 初始化
onMounted(() => {
  getList();
  loadCommissionCategoryOptions();
});

// 获取产品列表
const getList = async () => {
  loading.value = true;
  try {
    const response = await getProductList({
      ...queryParams,
      page: pagination.page,
      page_size: pagination.pageSize
    });
    productList.value = response.results || [];
    pagination.total = response.count || 0;
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 加载提成分类选项
const loadCommissionCategoryOptions = async () => {
  try {
    const response = await getCommissionCategoryList();
    commissionCategoryOptions.value = response.results || [];
  } catch (error) {
    console.error(error);
  }
};

// 获取产品标签数组
const getProductTags = (tagString) => {
  if (!tagString) return [];
  return tagString.split(',').filter(tag => tag.trim() !== '');
};

// 获取标签类型
const getTagType = (tag) => {
  const tagTypes = ['', 'success', 'warning', 'danger', 'info'];
  const hash = tag.split('').reduce((acc, char) => {
    return acc + char.charCodeAt(0);
  }, 0);
  return tagTypes[hash % tagTypes.length];
};

// 处理查询
const handleQuery = () => {
  pagination.page = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.product_name = '';
  queryParams.product_tag = '';
  handleQuery();
};

// 处理添加
const handleAdd = () => {
  dialogTitle.value = '添加产品';
  productForm.product_name = '';
  productForm.product_tag = '';
  productForm.commission_category = null;
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑产品';
  try {
    const response = await getProduct(row.id);
    productForm.id = response.id;
    productForm.product_name = response.product_name;
    productForm.product_tag = response.product_tag;
    productForm.commission_category = response.commission_category;
    dialogVisible.value = true;
  } catch (error) {
    console.error(error);
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该产品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProduct(row.id);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error(error);
    }
  }).catch(() => {});
};

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  
  ElMessageBox.confirm('确认要删除选中的产品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteProducts(selectedIds.value);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error(error);
    }
  }).catch(() => {});
};

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 提交表单
const submitForm = async () => {
  if (!productFormRef.value) return;
  
  await productFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (productForm.id) {
          await updateProduct(productForm.id, productForm);
          ElMessage.success('更新成功');
        } else {
          await createProduct(productForm);
          ElMessage.success('添加成功');
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error(error);
      }
    }
  });
};

// 处理导出
const handleExport = async () => {
  try {
    const response = await exportProducts(queryParams);
    // 创建Blob链接并下载
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '产品数据.xlsx';
    link.click();
    URL.revokeObjectURL(link.href);
  } catch (error) {
    console.error(error);
  }
};

// 处理导入
const handleImport = () => {
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  importFile.value = null;
  importDialogVisible.value = true;
};

// 处理文件变化
const handleFileChange = (file) => {
  if (!file) {
    importFile.value = null;
    return false;
  }
  
  // 检查是否是Excel文件
  const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase());
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件(.xlsx, .xls)');
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
    return false;
  }
  
  // 保存文件引用
  importFile.value = file.raw;
  ElMessage.success(`文件"${file.name}"准备就绪，请点击"开始导入"按钮开始导入`);
  return true;
};

// 处理文件拖拽
const handleDrop = (file) => {
  console.log('文件已拖拽到上传区域', file);
  ElMessage.success('文件已上传，请点击"开始导入"按钮');
};

// 处理超出文件数量限制
const handleExceed = () => {
  ElMessage.warning('只能上传1个文件，请先删除已选择的文件');
};

// 下载导入模板
const downloadTemplate = async () => {
  try {
    const response = await getImportTemplate();
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '产品导入模板.xlsx';
    link.click();
    URL.revokeObjectURL(link.href);
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败');
  }
};

// 提交导入
const submitImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请先选择或拖拽文件');
    return;
  }
  
  const formData = new FormData();
  formData.append('file', importFile.value);
  
  try {
    importLoading.value = true;
    ElMessage.info('正在处理导入请求，请稍候...');
    
    const response = await importProducts(formData);
    
    if (response.success) {
      ElMessage.success({
        message: `导入成功${response.imported_count ? '，共导入 ' + response.imported_count + ' 条记录' : ''}`,
        duration: 5000
      });
      importDialogVisible.value = false;
      // 刷新列表
      getList();
    } else {
      ElMessage.error({
        message: response.message || '导入失败',
        duration: 5000
      });
    }
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error({
      message: '导入失败: ' + (error.message || '未知错误'),
      duration: 5000
    });
  } finally {
    importLoading.value = false;
  }
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  getList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.page = val;
  getList();
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.app-card {
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  border: none;
  overflow: hidden;
  transition: all 0.3s ease;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 12px;
}

.search-input {
  width: 280px;
  border-radius: 8px;
}

.search-button, .reset-button {
  border-radius: 8px;
  height: 40px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.search-button {
  background-color: #0071e3;
  border-color: #0071e3;
}

.search-button:hover {
  background-color: #0077ed;
  border-color: #0077ed;
  transform: translateY(-1px);
}

.reset-button {
  color: #606266;
  background-color: #f5f7fa;
  border-color: #f5f7fa;
}

.reset-button:hover {
  background-color: #e4e7ed;
  border-color: #e4e7ed;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  width: 100%;
}

.left-buttons {
  display: flex;
  gap: 10px;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.action-button {
  border-radius: 8px;
  padding: 10px 16px;
  height: 40px;
  font-weight: 500;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.add-button {
  background-color: #0071e3;
  border-color: #0071e3;
}

.export-button {
  background-color: #67c23a;
  border-color: #67c23a;
}

.import-button {
  background-color: #0071e3;
  border-color: #0071e3;
}

.action-button:hover {
  transform: translateY(-1px);
}

.button-icon {
  margin-right: 6px;
}

.data-table {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--border) {
  border-radius: 8px;
  overflow: hidden;
}

.table-button {
  font-size: 14px;
  font-weight: 500;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.product-tag {
  border-radius: 20px;
  padding: 2px 10px;
  margin: 0;
  font-size: 12px;
}

.table-pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.pagination {
  --el-pagination-button-bg-color: #f5f7fa;
  --el-pagination-hover-color: #0071e3;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #0071e3;
}

.custom-dialog {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.dialog-form {
  padding: 0 12px;
}

.form-input {
  width: 100%;
  border-radius: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-button, .submit-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}

.submit-button {
  background-color: #0071e3;
  border-color: #0071e3;
}

.submit-button:hover {
  background-color: #0077ed;
  border-color: #0077ed;
}

.import-container {
  padding: 0 12px;
}

.import-tips {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  font-size: 14px;
}

.import-tips p {
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}

.import-tips ol {
  padding-left: 20px;
  margin: 0;
  color: #606266;
}

.template-download {
  margin-bottom: 20px;
}

.download-button {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #0071e3;
}

.download-button:hover {
  color: #0077ed;
}

.upload-demo {
  margin-bottom: 20px;
}

:deep(.el-upload--text) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-radius: 8px;
  border: 2px dashed #dcdfe6;
}

:deep(.el-upload-dragger:hover) {
  border-color: #0071e3;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: #0071e3;
  margin-bottom: 10px;
}

:deep(.el-upload__text) {
  font-size: 16px;
  color: #606266;
}

:deep(.el-upload__text em) {
  color: #0071e3;
  font-style: normal;
  cursor: pointer;
}

:deep(.el-upload__tip) {
  font-size: 13px;
  color: #909399;
  line-height: 1.5;
}
</style> 